<template>
  <view class="settlement-container">
    <!-- 用户信息卡片 -->
    <view class="card user-info-card">
      <view class="card-header">
        <text>用户信息</text>
      </view>
      <view class="card-content">
        <text>用户名: {{ userInfo.username }}</text>
        <text>电话: {{ userInfo.phone }}</text>
        <text>VIP等级: {{ userInfo.name }}</text>
      </view>
    </view>

    <!-- 预约商品信息卡片 -->
    <view class="card appointment-info-card">
      <view class="card-header">
        <text>预约商品信息</text>
      </view>
      <view class="card-content">
        <view class="product-item">
          <image :src="appointmentInfo.img" class="product-image"></image>
          <view class="product-info">
            <text class="product-name">{{ appointmentInfo.name }}</text>
            <view class="product-prices">
				<text class="product-discount-price">￥{{ appointmentInfo.discount_price }}</text>
              <text class="product-original-price">￥{{ appointmentInfo.original_price }}</text>
              
            </view>
          </view>
        </view>
        <view class="appointment-time">
          <text>预约时间: {{ formatDate(appointmentInfo.appointment_time) }}</text>
        </view>
        <view class="appointment-deadline">
          <text>截止时间: {{ formatDate(appointmentInfo.deadline) }}</text>
        </view>
      </view>
    </view>

    <!-- 留言卡片 -->
    <view class="card message-card">
      <view class="card-header">
        <text>留言</text>
      </view>
      <view class="card-content">
        <input v-model="message" type="text" placeholder="请输入留言（最多30字）" maxlength="30" />
      </view>
    </view>

    <!-- 会员折扣 -->
    <view class="card membership-discount-card">
      <view class="card-header">
        <text>会员折扣</text>
      </view>
      <view class="card-content">
        <text>折扣: {{ userInfo.discount }}%</text>
      </view>
    </view>

    <!-- 合计和立即预约按钮 -->
    <view class="total-section">
      <view class="total-amount">
        <text>合计:</text>
        <text class="amount-value">￥{{ totalAmount }}</text>
      </view>
      <view class="submit-order">
        <button @click="showPaymentMethods">立即预约</button>
      </view>
    </view>

    <!-- 支付方式弹窗 -->
    <view class="payment-methods" v-if="showPaymentMethodsDialog" @click="closePaymentMethodsDialog">
      <view class="payment-methods-content" @click.stop>
        <button @click="payWithWechat" class="payment-button">微信支付</button>
        <button @click="payWithAlipay" class="payment-button">支付宝支付</button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      userInfo: {},
      appointmentInfo: {},
      message: '',
      totalAmount: 0,
      showPaymentMethodsDialog: false,
    };
  },
  onLoad(options) {
    this.service_id = options.service_id;
    this.appointment_id = options.appointment_id;
    this.fetchUserInfo();
    this.fetchAppointmentInfo(this.appointment_id);
  },
  methods: {
    fetchUserInfo() {
      const token = uni.getStorageSync('Authorization');
      uni.request({
        url: 'http://localhost:8887/user/userInfo',
        method: 'GET',
        header: {
          'Authorization': token,
          'Content-Type': 'application/json',
        },
        success: (res) => {
          if (res.data.code === 200 && res.data.success) {
            this.userInfo = res.data.data;
            this.calculateTotal();
          } else {
            uni.showToast({
              title: '获取用户信息失败',
              icon: 'none',
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: '请求失败，请检查网络或链接的合法性',
            icon: 'none',
          });
        },
      });
    },
    fetchAppointmentInfo(appointmentId) {
      uni.request({
        url: `http://localhost:8887/Appointmentslot/select?id=${appointmentId}`,
        method: 'GET',
        success: (res) => {
          if (res.data.code === 200 && res.data.success) {
            this.appointmentInfo = res.data.data;
            this.totalAmount = this.calculateDiscountedPrice(this.appointmentInfo.discount_price);
          } else {
            uni.showToast({
              title: '获取预约商品信息失败',
              icon: 'none',
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: '请求失败，请检查网络或链接的合法性',
            icon: 'none',
          });
        },
      });
    },
    calculateTotal() {
      if (this.appointmentInfo && this.userInfo) {
        this.totalAmount = this.calculateDiscountedPrice(this.appointmentInfo.discount_price);
      }
    },
    calculateDiscountedPrice(price) {
      return (price * (this.userInfo.discount / 100)).toFixed(2);
    },
    showPaymentMethods() {
      this.showPaymentMethodsDialog = true;
    },
    closePaymentMethodsDialog() {
      this.showPaymentMethodsDialog = false;
    },
    payWithWechat() {
      this.processPayment('微信支付');
    },
    payWithAlipay() {
      this.processPayment('支付宝支付');
    },
	goToOrderDetails(orderId) {
	  uni.navigateTo({
	    url: `/pages/serviceorderdetails/serviceorderdetails?id=${orderId}`
	  });
	},
	formatDate(value) {
		const date = new Date(value);
		return new Intl.DateTimeFormat('zh-CN', {
			year: 'numeric',
			month: '2-digit',
			day: '2-digit',
			hour: '2-digit',
			minute: '2-digit',
			second: '2-digit',
			hour12: false
		}).format(date);
	},
    processPayment(paymentMethod) {
      const token = uni.getStorageSync('Authorization');
      const url = 'http://localhost:8887/Serviceappointment/add';
      const orderData = {
        appointmentslot_id: this.appointment_id, 
        total_amount: this.totalAmount,
        payment_method: paymentMethod,
        message: this.message,
      };
      const header = {
        'Authorization': token,
        'Content-Type': 'application/json'
      };
      uni.request({
        url,
        method: 'POST',
        header,
        data: orderData,
        success: (res) => {
          if (res.data.success) {
            uni.showToast({
              title: '预约成功',
              icon: 'success'
            });
            this.closePaymentMethodsDialog();
            const orderId = res.data.data.id; 
            this.goToOrderDetails(orderId); 
          } else {
            uni.showToast({
              title: '预约失败',
              icon: 'none'
            });
            this.closePaymentMethodsDialog();
          }
        },
        fail: () => {
          uni.showToast({
            title: '请求失败',
            icon: 'none'
          });
          this.closePaymentMethodsDialog();
        }
      });
    },
  },
};
</script>

<style>
.settlement-container {
  position: relative;
  padding: 15px;
  overflow-y: auto; /* 允许页面滑动 */
  height: 100%; /* 设置容器高度为100% */
}

.card {
  background-color: #f9f9f9;
  border: 1px solid #eaeaea;
  margin-bottom: 20rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.card-header {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.card-content {
  font-size: 28rpx;
  color: #555;
  display: flex;
  flex-direction: column;
}

.user-info-card .card-content, .appointment-info-card .card-content {
  display: flex;
  flex-direction: column;
}

.product-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.product-image {
  width: 60px;
  height: 60px;
  margin-right: 10px;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.product-name {
  font-size: 28rpx;
  color: #333;
  white-space: normal;
  word-break: break-word;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-prices {
width: 100%;
}

.product-original-price {
  text-decoration: line-through;
  font-size: 14px;
  color: #999;
}
.product-discount-price {
  font-size: 18px;
  color: #e4393c;
  font-weight: bold;
}
.appointment-time, .appointment-deadline {
  font-size: 24rpx;
  color: #555;
  margin-top: 10px;
}

.message-card input {
  border: 1px solid #eee;
  padding: 10px;
  border-radius: 4px;
  width: 100%;
  font-size: 28rpx;
}

.total-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
background-color: white;
padding: 20rpx;
box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
display: flex;
justify-content: space-between;
align-items: center;
z-index: 1000;
}

.total-amount {
font-size: 32rpx;
color: #333;
}

.amount-value {
font-size: 36rpx;
color: #ff9966;
}

.submit-order button {
background-color: #ff9966;
color: white;
border: none;
padding: 10px;
width: 100%;
}

.payment-methods {
position: fixed;
left: 0;
right: 0;
bottom: 0;
top: 0;
background-color: rgba(0, 0, 0, 0.6);
display: flex;
justify-content: flex-end;
align-items: flex-end;
z-index: 1001;
}

.payment-methods-content {
display: flex;
flex-direction: row;
justify-content: center;
background-color: white;
padding: 10px;
width: 100%;
box-sizing: border-box;
border-top: 1px solid #eee;
}

.payment-methods-content .payment-button {
flex: 1;
height: 80rpx;
background-color: #ff9966;
color: white;
border: none;
font-size: 28rpx;
margin: 0 10px;
}

.membership-discount-card {
margin-bottom: 20rpx;
}

/* 新增会员折扣样式 */
.membership-discount {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 10px;
font-size: 28rpx;
color: #555;
}

.discount-value {
color: #ff9966;
font-size: 30rpx;
}

/* 调整预约商品信息卡片样式 */
.appointment-info-card .card-content {
display: flex;
flex-direction: column;
}

.appointment-info-card .product-item {
flex-direction: row;
align-items: center;
}

.appointment-info-card .product-name, .appointment-info-card .product-prices {
margin-left: 10px;
}

.appointment-time, .appointment-deadline {
margin-top: 10px;
}

/* 底部会员折扣与页面底部的距离 */
.membership-discount-card {
margin-bottom: 20rpx;
}
</style>